package com.lishe.lishe.lishe.module.myorder.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lishe.base.common.config.Constants;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.Arith;
import com.lishe.lishe.lishe.common.CommonUtils;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.myorder.activity.OrderDetailActivity;
import com.lishe.lishe.lishe.module.myorder.bean.OrderListBean;
import com.lishe.lishe.lishe.module.myorder.bean.Products;
import com.lishe.lishe.lishe.module.myorder.bean.TradePaybillData;
import com.lishe.lishe.lishe.module.myorder.view.RemindSendDialog;
import com.lishe.lishe.lishe.utils.DefaultCountDownTimer;
import com.lishe.lishe.lishe.utils.FormatUtil;
import com.lishe.lishe.lishe.widget.ConfirmDialog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by lwa on 2017/8/11.
 * 订单对象
 */

public class OrderAdapter0 extends RecyclerView.Adapter {
    private Activity context;
    private String[] orderBtnType;
    private List<OrderListBean.DataBean.ListBean> mOrderList;
    private ConfirmDialog.Builder callPhoneDialog;
    private DefaultCountDownTimer timer;
    private AdapterListener mListener;

    public interface AdapterListener {
        void onTimerFinish();
    }

    public OrderAdapter0(Activity context, List<OrderListBean.DataBean.ListBean> list, AdapterListener listener) {
        this.context = context;
        this.mOrderList = list;
        this.mListener = listener;
        orderBtnType = context.getResources().getStringArray(R.array.order_btn_type);
        createCallPhone();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order_adapter, null);
        OrderAdapterViewHolder viewHolder=new OrderAdapterViewHolder(view);
        return viewHolder;
    }

    String windowMsg;//弹窗内容
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final OrderAdapterViewHolder orderHolder = (OrderAdapterViewHolder) holder;
        final OrderListBean.DataBean.ListBean order = mOrderList.get(position);
        switch (order.getOrder_status()) {
            case "1"://超时失效
            case "2"://用户手动取消
            case "3"://被客服取消
                orderHolder.btnPay.setVisibility(View.GONE);
                orderHolder.btnCancle.setVisibility(View.GONE);
                orderHolder.orderType.setText("订单已失效");
                break;
            case "4"://待付款
                orderHolder.btnCancle.setVisibility(View.VISIBLE);
                orderHolder.btnPay.setVisibility(View.VISIBLE);
                orderHolder.btnCancle.setText(orderBtnType[0]);
                orderHolder.btnPay.setText(orderBtnType[4]);
                windowMsg = context.getString(R.string.iscancle_order);
                orderHolder.orderType.setText("待付款");

                //倒计时
                try {
                    long _30min = 60 * 30 * 1000;
                    long d1 = Long.parseLong(order.getSys_time()) * 1000;
                    long d2 = Long.parseLong(order.getCreated_time()) * 1000;
                    long diff = _30min - (d1 - d2);
                    timer = new DefaultCountDownTimer(orderHolder.btnPay, "付款 ", "", diff, 1000,new DefaultCountDownTimer.Finish() {
                        @Override
                        public void onFinish() {
                            mListener.onTimerFinish();
                        }
                    });
                    timer.start();
                    orderHolder.btnPay.setTag(timer);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if(order.getIs_overdue().equals("0")){//订单已失效
                    orderHolder.btnCancle.setVisibility(View.GONE);
                    orderHolder.btnPay.setVisibility(View.GONE);
                    orderHolder.orderType.setText("订单已失效");
                }
                break;
            case "5"://待发货
                orderHolder.btnCancle.setVisibility(View.VISIBLE);
                orderHolder.btnPay.setVisibility(View.GONE);
                orderHolder.btnCancle.setText(orderBtnType[1]);
                orderHolder.orderType.setText("待发货");
                break;
            case "6"://待收货
                orderHolder.btnCancle.setVisibility(View.GONE);
                orderHolder.btnCancle.setVisibility(View.VISIBLE);
                orderHolder.btnCancle.setText(orderBtnType[2]);
                orderHolder.btnPay.setVisibility(View.VISIBLE);
                orderHolder.btnPay.setText(orderBtnType[3]);
                windowMsg = context.getString(R.string.isreceive_order);
                orderHolder.orderType.setText("待收货");
                break;
            case "7"://待评论
            case "8"://已完成
                orderHolder.btnCancle.setVisibility(View.VISIBLE);
                orderHolder.btnCancle.setText("查看详情");
                orderHolder.btnPay.setVisibility(View.GONE);
                orderHolder.orderType.setText("已完成");
                break;
            case "9"://退货
                orderHolder.btnCancle.setVisibility(View.VISIBLE);
                orderHolder.btnCancle.setText("查看详情");
                orderHolder.btnPay.setVisibility(View.GONE);
                orderHolder.orderType.setText("已退货");
                break;
            default:
                orderHolder.btnPay.setVisibility(View.GONE);
                orderHolder.btnCancle.setVisibility(View.GONE);
                orderHolder.orderType.setText("未知状态");
                break;
        }
        SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        Date date = new Date(Long.parseLong(order.getCreated_time()) * 1000);
        orderHolder.order_time.setText(format.format(date));


        Log.i("money", Arith.mul(Double.parseDouble(order.getMoney()), 100) + ".....");
        orderHolder.orderTotalMoney.setText(FormatUtil.numFormat(Arith.mul(Double.parseDouble(order.getMoney()), 100)));
        //订单商品数量
        int count = 0;
        for (int i = 0; i < order.getTrade_paybillData().size(); i++) {
            if (order.getTrade_paybillData().get(i).getProducts() != null) {
                count += order.getTrade_paybillData().get(i).getProducts().size();
            }
        }
        orderHolder.goodsCount.setText("共" + count + "件");
        if ("5".equals(order.getOrder_status()) && order.isRemindSend()) {
            orderHolder.btnCancle.setEnabled(false);
            orderHolder.btnCancle.setTextColor(context.getResources().getColor(R.color.gray_9));
        } else {
            orderHolder.btnCancle.setEnabled(true);
            orderHolder.btnCancle.setTextColor(context.getResources().getColor(R.color.gray_3));
        }
        orderHolder.btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("5".equals(order.getOrder_status())) { //待发货
                    new RemindSendDialog(context).show();
                    order.setRemindSend(true);
                    notifyDataSetChanged();
                } else if ("7".equals(order.getOrder_status()) || "8".equals(order.getOrder_status()) || "9".equals(order.getOrder_status())) {
                    //已退款 已完成
                    Intent i = new Intent(context, OrderDetailActivity.class);
                    i.putExtra(Constants.TID, mOrderList.get(position).getTrade_paybillData().get(0).getTid());
                    i.putExtra(Constants.PAYMENTID, mOrderList.get(position).getPayment_id());
                    i.putExtra(Constants.ISREMINDSEND, order.isRemindSend());
                    context.startActivity(i);
                }
                if (buttonOnclikListener != null) {
                    buttonOnclikListener.graButtonLitener(order, position);
                }
            }
        });
        orderHolder.btnPay.setOnClickListener(new View.OnClickListener() {//立即付款
            @Override
            public void onClick(View view) {
                if (buttonOnclikListener != null) {
                    buttonOnclikListener.redButtonLitener(order, position);
                }
            }
        });
        //跳转至订单详情
        orderHolder.total.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(context, OrderDetailActivity.class);
                i.putExtra(Constants.TID, "4".equals(mOrderList.get(position).getOrder_status())
                        || "3".equals(mOrderList.get(position).getOrder_status())
                        || "2".equals(mOrderList.get(position).getOrder_status())
                        || "1".equals(mOrderList.get(position).getOrder_status()) ? "" : mOrderList.get(position).getTrade_paybillData().get(0).getTid());
                i.putExtra(Constants.PAYMENTID, mOrderList.get(position).getPayment_id());
                i.putExtra(Constants.ISREMINDSEND, order.isRemindSend());
                context.startActivity(i);
            }
        });

        GoodsViewHolder goodsHolder;
        orderHolder.goodsLayout.removeAllViews();
        for (int i = 0; i < order.getTrade_paybillData().size(); i++) {
            TradePaybillData business = order.getTrade_paybillData().get(i);
            for (int j = 0; j < business.getProducts().size(); j++) {//商品
                Products good = business.getProducts().get(j);
                View v = View.inflate(context, R.layout.item_order_adapter_good, null);
                goodsHolder = new GoodsViewHolder(v);
                goodsHolder.goodsCount.setText("x" + good.getNum());
                goodsHolder.goodsName.setText(good.getTitle());
                goodsHolder.goodsSpec.setText(good.getSpec_info());
                goodsHolder.goodsPrice.setText("¥" + good.getPrice());
                if (good.getPrice().equals(good.getOriginal_price())) {
                    goodsHolder.originalPrice.setVisibility(View.GONE);
                } else {
                    goodsHolder.originalPrice.setVisibility(View.VISIBLE);
                    goodsHolder.originalPrice.setText("¥" + good.getOriginal_price());
                    goodsHolder.originalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                }
                ImageLoaderUtils.displayImage(context, good.getPic_path(), goodsHolder.goodsImg);
                orderHolder.goodsLayout.addView(v);
            }
        }
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        super.onViewRecycled(holder);
        OrderAdapterViewHolder mHolder = (OrderAdapterViewHolder) holder;
        DefaultCountDownTimer timer = (DefaultCountDownTimer) mHolder.btnPay.getTag();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public int getItemCount() {
        return mOrderList.size();
    }

    /**
     * 订单holder
     */
    class OrderAdapterViewHolder extends RecyclerView.ViewHolder{

        /*private ImageView QQ;
        private ImageView phone;*/
        private TextView btnPay;
        private TextView btnCancle;
        private TextView orderTotalMoney;
        private TextView goodsCount;
        private LinearLayout goodsLayout;
        private TextView orderType;
        private View total;
        private TextView order_time;

        OrderAdapterViewHolder(View v) {
            super(v);
            goodsCount = v.findViewById(R.id.goods_count);
            orderTotalMoney = v.findViewById(R.id.pay_money);
            //QQ = v.findViewById(R.id.order_qq_img);
            //phone = v.findViewById(R.id.order_phone_img);
            btnPay = v.findViewById(R.id.pay_button);
            btnCancle = v.findViewById(R.id.cancle_button);
            goodsLayout = v.findViewById(R.id.goods_layout);
            orderType = v.findViewById(R.id.order_type);
            total = v.findViewById(R.id.total);
            order_time = v.findViewById(R.id.order_time);
        }
    }

    /**
     * 商品holder
     */
    class GoodsViewHolder extends RecyclerView.ViewHolder{
        public ImageView goodsImg;
        public TextView goodsName;
        public TextView goodsSpec;
        public TextView goodsPrice;
        public TextView goodsCount;
        public TextView originalPrice;

        GoodsViewHolder(View v) {
            super(v);
            goodsImg = v.findViewById(R.id.goods_img);
            goodsName = v.findViewById(R.id.goods_name);
            goodsSpec = v.findViewById(R.id.goods_spec);
            goodsPrice = v.findViewById(R.id.goods_price);
            goodsCount = v.findViewById(R.id.goods_count);
            originalPrice = v.findViewById(R.id.original_price);
        }
    }

    /**
     * 拨号
     */
    private void createCallPhone() {
        callPhoneDialog = new ConfirmDialog.Builder(context);
        callPhoneDialog.setContent(Globals.LISHE_PHONE);
        callPhoneDialog.setContentGravity(Gravity.CENTER_HORIZONTAL);
        callPhoneDialog.setPositiveButton("确定", new ConfirmDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(ConfirmDialog dialog) {
                dialog.dismiss();
                CommonUtils.callPhone((Activity) context, Globals.LISHE_PHONE);
            }
        });
    }

    /**
     * 按钮的回调
     */
    ButtonOnclikListener buttonOnclikListener;

    public interface ButtonOnclikListener {
        void redButtonLitener(OrderListBean.DataBean.ListBean orderObject, int position);
        void graButtonLitener(OrderListBean.DataBean.ListBean orderObject, int position);
    }

    public void setOnButtonListener(ButtonOnclikListener buttonOnclikListener) {
        this.buttonOnclikListener = buttonOnclikListener;
    }
}
